<?php
/**
 * PHP-T超轻量级PHP开发框架
 *
 * @author    哈尔滨伟成科技有限公司 QQ77701950
 * @copyright Copyright (c) 2023
 * @license   PHP-T 遵循Apache2开源协议发布，需保留开发者信息。
 * @link      http://www.ourphp.net
**/

namespace PHPt;
use PHPt\lib\html;
use PHPt\lib\style;

class ourphp_app
{
	
	public function __construct()
	{
		
	}
	
	public function run()
	{
		self::geturl();
	}
	
	private static function geturl()
	{
		
		global $config;
		$weburl = strip_tags(htmlspecialchars(stripslashes($_SERVER['REQUEST_URI'])));
		if($weburl == '/' || $weburl == '/index.php' || empty($weburl))
		{
			
			$urlinfo[0] = $config['default_model'];
			$urlinfo[1] = $config['default_controller'];
			$urlinfo[2] = $config['default_function'];
			
			$par = [];
			
		}else{
			
			$newweburl = str_replace("/index.php/","",$weburl);
			$newweburl = trim($newweburl,"/");
			$newweburl = explode("/",$newweburl);
			
			$urlinfo[0] = $newweburl[0];
			$urlinfo[1] = $newweburl[1];
			$urlinfo[2] = $newweburl[2];
			
			$par = self::parameter($newweburl);
			if($urlinfo[0] == 'version'): html::E(style::E(PHPT . " " . $config['version'])); exit; endif;
		}
		
		self::judgmentnull($urlinfo[0], $urlinfo[1], $urlinfo[2]);
		self::controller($urlinfo[0], $urlinfo[1], $urlinfo[2], $par, $config);
		
	}
	
	private static function parameter($array = [])
	{
		return $array;
	}
	
	private static function judgmentnull($model, $controller, $function)
	{
		$newmodel = APP_ROOT . $model;
		$newcontroller = APP_ROOT . $model . OP . "controller" . OP . $controller . "_controller.php";
		$newfunction = APP_NAMESPACE . "\\" . $model . "\\" . "controller" . "\\" . $controller . "_controller";
		$newview = APP_ROOT . $model . OP . "view" . OP . $controller . ".php";
		
		if(!is_dir($newmodel))
		{
			html::E(style::E("模型 ".$newmodel." 未找到"));
			exit();
		}
		if(!file_exists($newcontroller))
		{
			html::E(style::E("控制器 ".$newcontroller." 未找到"));
			exit();
		}
		if(!class_exists($newfunction))
		{
			html::E(style::E("控制器类 ".$newfunction." 未找到"));
			exit();
		}
		if(!method_exists($newfunction, $function . "_function"))
		{
			html::E(style::E("控制器方法 ".$newfunction . "\\" . $function . "_function"." 未找到"));
			exit();
		}
		if(!file_exists($newview))
		{
			html::E(style::E("模板 ".$newview." 未找到"));
			exit();
		}
	}
	
	public static function controller($model, $controller, $function, $geturlstr = [], $config)
	{
		$viewpath = APP_ROOT . $model . OP . "view" . OP . $controller . ".php";
		$newmodel = '\\' . APP_NAMESPACE . '\\' . $model . '\model\\' . $controller . '_model';
		$newcontroller = '\\' . APP_NAMESPACE . '\\' . $model . '\controller\\' . $controller . '_controller';
		$newfunction = $function . "_function";
		
		$new = new $newcontroller($viewpath, $geturlstr, $config, $newmodel, $newfunction);
		$new -> $newfunction();
	}
	
}
?>